<template>
	<view class="container">
		<view class="header">
			<text class="title">📊 健康数据记录</text>
			<text class="subtitle">请填写您的健康数据，我们将为您提供个性化分析</text>
		</view>

		<view class="form-container">
			<!-- 基本信息 -->
			<view class="form-section">
				<text class="section-title">基本信息</text>
				
				<view class="form-item">
					<text class="label">年龄</text>
					<input class="input" :class="{ 'input-error': errors.age }" type="number" v-model="formData.age" placeholder="请输入年龄" @blur="validateAge" />
					<text v-if="errors.age" class="error-text">{{errors.age}}</text>
				</view>
				
				<view class="form-item">
					<text class="label">性别</text>
					<picker class="picker" :value="genderIndex" :range="genderOptions" @change="onGenderChange">
						<view class="picker-text">{{genderOptions[genderIndex]}}</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="label">身高 (cm)</text>
					<input class="input" :class="{ 'input-error': errors.height }" type="digit" v-model="formData.height" placeholder="请输入身高" @blur="validateHeight" />
					<text v-if="errors.height" class="error-text">{{errors.height}}</text>
				</view>
				
				<view class="form-item">
					<text class="label">体重 (kg)</text>
					<input class="input" :class="{ 'input-error': errors.weight }" type="digit" v-model="formData.weight" placeholder="请输入体重" @blur="validateWeight" />
					<text v-if="errors.weight" class="error-text">{{errors.weight}}</text>
				</view>
			</view>

			<!-- 血压数据 -->
			<view class="form-section">
				<text class="section-title">血压数据</text>
				
				<view class="form-item">
					<text class="label">收缩压 (mmHg)</text>
					<input class="input" :class="{ 'input-error': errors.systolic }" type="number" v-model="formData.systolic" placeholder="如：120" @blur="validateSystolic" />
					<text v-if="errors.systolic" class="error-text">{{errors.systolic}}</text>
				</view>
				
				<view class="form-item">
					<text class="label">舒张压 (mmHg)</text>
					<input class="input" :class="{ 'input-error': errors.diastolic }" type="number" v-model="formData.diastolic" placeholder="如：80" @blur="validateDiastolic" />
					<text v-if="errors.diastolic" class="error-text">{{errors.diastolic}}</text>
				</view>
			</view>

			<!-- 生活习惯 -->
			<view class="form-section">
				<text class="section-title">生活习惯</text>
				
				<view class="form-item">
					<text class="label">每日运动时长</text>
					<picker class="picker" :value="exerciseIndex" :range="exerciseOptions" @change="onExerciseChange">
						<view class="picker-text">{{exerciseOptions[exerciseIndex]}}</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="label">睡眠时长</text>
					<picker class="picker" :value="sleepIndex" :range="sleepOptions" @change="onSleepChange">
						<view class="picker-text">{{sleepOptions[sleepIndex]}}</view>
					</picker>
				</view>
				
				<view class="form-item">
					<text class="label">吸烟情况</text>
					<picker class="picker" :value="smokeIndex" :range="smokeOptions" @change="onSmokeChange">
						<view class="picker-text">{{smokeOptions[smokeIndex]}}</view>
					</picker>
				</view>
			</view>

			<!-- 症状描述 -->
			<view class="form-section">
				<text class="section-title">症状描述</text>
				<textarea class="textarea" v-model="formData.symptoms" placeholder="请描述您最近的身体状况或不适症状（可选）" />
			</view>
		</view>

		<!-- 保存按钮 -->
		<view class="button-container">
			<button class="save-btn" @click="saveHealthData">保存健康数据</button>
		</view>

		<!-- 数据预览 -->
		<view class="preview-section" v-if="healthData">
			<text class="preview-title">📈 数据预览</text>
			<view class="preview-content">
				<view class="preview-item">
					<text class="preview-label">BMI指数</text>
					<text class="preview-value">{{healthData.bmi}}</text>
				</view>
				<view class="preview-item">
					<text class="preview-label">血压状态</text>
					<text class="preview-value">{{healthData.bloodPressureStatus}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					age: '',
					gender: '男',
					height: '',
					weight: '',
					systolic: '',
					diastolic: '',
					exercise: '30分钟以下',
					sleep: '6-8小时',
					smoke: '不吸烟',
					symptoms: ''
				},
				errors: {
					age: '',
					height: '',
					weight: '',
					systolic: '',
					diastolic: ''
				},
				genderOptions: ['男', '女'],
				genderIndex: 0,
				exerciseOptions: ['30分钟以下', '30-60分钟', '60分钟以上'],
				exerciseIndex: 0,
				sleepOptions: ['6小时以下', '6-8小时', '8小时以上'],
				sleepIndex: 1,
				smokeOptions: ['不吸烟', '偶尔吸烟', '经常吸烟'],
				smokeIndex: 0,
				healthData: null
			}
		},
		onLoad() {
			this.loadHealthData()
		},
		onShow() {
			// 登录校验
			const userInfo = uni.getStorageSync('userInfo')
			if (!userInfo) {
				uni.redirectTo({ url: '/pages/login/login' })
				return
			}
			
			// 检查是否有健康数据，如果没有则重置表单
			const healthData = uni.getStorageSync('healthData')
			if (!healthData) {
				// 没有健康数据时，重置表单为初始状态
				this.healthData = null
				this.resetFormData()
				console.log('用户切换后，健康数据页面已重置')
			} else {
				// 有健康数据时，正常加载
				this.loadHealthData()
			}
		},
		methods: {
			// 数据校验方法
			validateAge() {
				const age = parseInt(this.formData.age)
				if (!this.formData.age) {
					this.errors.age = '请输入年龄'
					return false
				}
				if (isNaN(age) || age < 1 || age > 120) {
					this.errors.age = '年龄应在1-120岁之间'
					return false
				}
				this.errors.age = ''
				return true
			},
			
			validateHeight() {
				const height = parseFloat(this.formData.height)
				if (!this.formData.height) {
					this.errors.height = '请输入身高'
					return false
				}
				if (isNaN(height) || height < 50 || height > 250) {
					this.errors.height = '身高应在50-250cm之间'
					return false
				}
				this.errors.height = ''
				return true
			},
			
			validateWeight() {
				const weight = parseFloat(this.formData.weight)
				if (!this.formData.weight) {
					this.errors.weight = '请输入体重'
					return false
				}
				if (isNaN(weight) || weight < 20 || weight > 300) {
					this.errors.weight = '体重应在20-300kg之间'
					return false
				}
				this.errors.weight = ''
				return true
			},
			
			validateSystolic() {
				if (!this.formData.systolic) {
					this.errors.systolic = ''
					return true // 血压可选
				}
				const systolic = parseInt(this.formData.systolic)
				if (isNaN(systolic) || systolic < 60 || systolic > 250) {
					this.errors.systolic = '收缩压应在60-250mmHg之间'
					return false
				}
				this.errors.systolic = ''
				return true
			},
			
			validateDiastolic() {
				if (!this.formData.diastolic) {
					this.errors.diastolic = ''
					return true // 血压可选
				}
				const diastolic = parseInt(this.formData.diastolic)
				if (isNaN(diastolic) || diastolic < 40 || diastolic > 150) {
					this.errors.diastolic = '舒张压应在40-150mmHg之间'
					return false
				}
				this.errors.diastolic = ''
				return true
			},
			
			validateBloodPressure() {
				if (this.formData.systolic && this.formData.diastolic) {
					const systolic = parseInt(this.formData.systolic)
					const diastolic = parseInt(this.formData.diastolic)
					if (systolic <= diastolic) {
						this.errors.systolic = '收缩压应大于舒张压'
						this.errors.diastolic = '舒张压应小于收缩压'
						return false
					}
				}
				return true
			},
			
			validateAll() {
				const validations = [
					this.validateAge(),
					this.validateHeight(),
					this.validateWeight(),
					this.validateSystolic(),
					this.validateDiastolic(),
					this.validateBloodPressure()
				]
				return validations.every(v => v === true)
			},
			
			onGenderChange(e) {
				this.genderIndex = e.detail.value
				this.formData.gender = this.genderOptions[this.genderIndex]
			},
			onExerciseChange(e) {
				this.exerciseIndex = e.detail.value
				this.formData.exercise = this.exerciseOptions[this.exerciseIndex]
			},
			onSleepChange(e) {
				this.sleepIndex = e.detail.value
				this.formData.sleep = this.sleepOptions[this.sleepIndex]
			},
			onSmokeChange(e) {
				this.smokeIndex = e.detail.value
				this.formData.smoke = this.smokeOptions[this.smokeIndex]
			},
			calculateBMI() {
				if (this.formData.height && this.formData.weight) {
					const height = parseFloat(this.formData.height) / 100
					const weight = parseFloat(this.formData.weight)
					return (weight / (height * height)).toFixed(1)
				}
				return null
			},
			getBloodPressureStatus() {
				if (this.formData.systolic && this.formData.diastolic) {
					const systolic = parseInt(this.formData.systolic)
					const diastolic = parseInt(this.formData.diastolic)
					
					if (systolic < 120 && diastolic < 80) return '正常'
					else if (systolic < 130 && diastolic < 80) return '正常偏高'
					else if (systolic < 140 && diastolic < 90) return '高血压前期'
					else return '高血压'
				}
				return '未测量'
			},
			saveHealthData() {
				// 清除所有错误
				this.errors = {
					age: '',
					height: '',
					weight: '',
					systolic: '',
					diastolic: ''
				}
				
				// 验证所有数据
				if (!this.validateAll()) {
					uni.showToast({
						title: '请检查输入数据',
						icon: 'none'
					})
					return
				}

				// 登录校验
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.redirectTo({ url: '/pages/login/login' })
					return
				}

				// 计算BMI和血压状态
				const bmi = this.calculateBMI()
				const bloodPressureStatus = this.getBloodPressureStatus()

				// 保存数据
				const healthData = {
					...this.formData,
					bmi: bmi,
					bloodPressure: `${this.formData.systolic || '--'}/${this.formData.diastolic || '--'}`,
					bloodPressureStatus: bloodPressureStatus,
					timestamp: Date.now()
				}
				console.log('保存的healthData:', healthData)
				uni.setStorageSync('healthData', healthData)
				this.healthData = healthData

				uni.showToast({
					title: '数据保存成功',
					icon: 'success'
				})

				// 跳转到分析页面
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/analysis/analysis'
					})
				}, 1500)
			},
			loadHealthData() {
				const data = uni.getStorageSync('healthData')
				if (data) {
					this.healthData = data
					// 填充表单数据
					this.formData = { ...data }
					
					// 设置选择器索引
					this.genderIndex = this.genderOptions.indexOf(data.gender)
					this.exerciseIndex = this.exerciseOptions.indexOf(data.exercise)
					this.sleepIndex = this.sleepOptions.indexOf(data.sleep)
					this.smokeIndex = this.smokeOptions.indexOf(data.smoke)
				} else {
					// 没有健康数据时，重置表单为初始状态
					this.healthData = null
					this.resetFormData()
				}
			},
			// 重置表单数据为初始状态
			resetFormData() {
				this.formData = {
					age: '',
					gender: '男',
					height: '',
					weight: '',
					systolic: '',
					diastolic: '',
					exercise: '30分钟以下',
					sleep: '6-8小时',
					smoke: '不吸烟',
					symptoms: ''
				}
				
				// 重置选择器索引
				this.genderIndex = 0
				this.exerciseIndex = 0
				this.sleepIndex = 1
				this.smokeIndex = 0
				
				// 清除错误信息
				this.errors = {
					age: '',
					height: '',
					weight: '',
					systolic: '',
					diastolic: ''
				}
				
				console.log('表单数据已重置为初始状态')
			}
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.subtitle {
		font-size: 26rpx;
		color: #666;
	}

	.form-container {
		margin-bottom: 30rpx;
	}

	.form-section {
		background: white;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.form-item {
		margin-bottom: 25rpx;
	}

	.label {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.input {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 10rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		background: #fafafa;
	}

	.input-error {
		border-color: #ff4757;
		background: #fff5f5;
	}

	.error-text {
		font-size: 24rpx;
		color: #ff4757;
		margin-top: 8rpx;
		display: block;
	}

	.picker {
		width: 100%;
		height: 80rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 10rpx;
		background: #fafafa;
	}

	.picker-text {
		line-height: 80rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		color: #333;
	}

	.textarea {
		width: 100%;
		height: 160rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 10rpx;
		padding: 20rpx;
		font-size: 28rpx;
		background: #fafafa;
	}

	.button-container {
		margin-bottom: 30rpx;
	}

	.save-btn {
		width: 100%;
		height: 90rpx;
		background: linear-gradient(135deg, #4CAF50, #45a049);
		color: white;
		border: none;
		border-radius: 15rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.preview-section {
		background: white;
		border-radius: 15rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}

	.preview-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 20rpx;
		display: block;
	}

	.preview-content {
		display: flex;
		justify-content: space-around;
	}

	.preview-item {
		text-align: center;
	}

	.preview-label {
		font-size: 24rpx;
		color: #666;
		display: block;
		margin-bottom: 10rpx;
	}

	.preview-value {
		font-size: 32rpx;
		font-weight: bold;
		color: #4CAF50;
	}
</style> 